//
//  SearchViewController.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/4/17.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchResultsControllerTableViewController.h"
#import "CityListDAO.h"
#import "RecommndCityListCell.h"
#import "searchCountyList.h"
#import "SectionIndexView.h"
@interface SearchViewController ()<UISearchResultsUpdating,UISearchBarDelegate,UISearchControllerDelegate,UITableViewDataSource,UITableViewDelegate,RecommndCityListCellDelegate>

@property (nonatomic, strong) UISearchController * searchController;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataSource;

@property (nonatomic, strong) NSMutableArray * countyListArray;
@property (nonatomic, strong) SearchResultsControllerTableViewController *searchResultTVC;

@property (nonatomic) NSInteger otherCount;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.hidesBackButton = YES;
    self.barBGAlpha = 1;
    [self setUp];
    
    [self setUpSearchController];
}

- (void)setUp {
    
    CGFloat H =  SCREEN_HEIGHT;
    CGFloat space = kNavigationBarHeight;
    self.tableView= [[UITableView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight,SCREEN_WIDTH, H - space ) style:UITableViewStylePlain];
    
    // ios 11  scrollvew 的位置调整
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
//    [self.tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"HeaderView"];
    
    [self.tableView registerClass:[RecommndCityListCell class] forCellReuseIdentifier:@"RecommndCityListCell"];
    
    
    if (![AppManager sharedManager].cityver || ![[AppManager sharedManager].version.cityver isEqualToString:[AppManager sharedManager].cityver]) {
        
        [NetAPIManager getCityListWithVersion:[AppManager sharedManager].version.cityver block:^(NSString *result, NSError *error) {
            
            if (!error) {
                
                [self loadDataSource];
            }
        }];
        return;
    }
    
    [self loadDataSource];
}

- (void)loadDataSource {
    [ActivityIndicatorView showHUDAddedTo:self.view];
    @weakify(self);
    [CityListDAO getCityListOrderByNearCity:self.currentCity block:^(NSArray *cityArray) {
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.dataSource = [NSMutableArray arrayWithArray:cityArray];
        
        self.countyListArray = [NSMutableArray arrayWithArray:[AppManager sharedManager].countryList];
        [self.tableView reloadData];
    }];
    
    NSMutableArray *array = [NSMutableArray array];
    
    for (searchCountyList * country in self.countyListArray) {
        [array addObject:[IGUtils firstCharactor:country.smartName]];
    }
    
    if (self.dataSource.count > 0) {
        [array insertObject:MYLocalizedString(@"CHANGECITY_NEAR", nil) atIndex:0];
    }
    
    if (self.gpsCity) {
        [array insertObject:@"GPS" atIndex:0];
    }
    
    UIView *lastView = [self.view viewWithTag:1000];
    
    if (lastView) {
        [lastView removeFromSuperview];
    }
   
    SectionIndexView *indexView = [[SectionIndexView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 30,kNavigationBarHeight , 30, SCREEN_HEIGHT - kNavigationBarHeight) sectionTitles:array];
//    indexView.backgroundColor = [UIColor whiteColor];
    indexView.delegate = self;
    indexView.tag = 1000;
    
    [self.view addSubview:indexView];
    
//    self.tableView.frame = CGRectMake(0, kNavigationBarHeight,SCREEN_WIDTH - 30, SCREEN_HEIGHT - kNavigationBarHeight);
}

- (void)selectIndex:(NSInteger)index {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:index];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

- (void)setUpSearchController {
    
    //创建 搜索使用的表示图控制器
    _searchResultTVC = [[SearchResultsControllerTableViewController alloc] initWithStyle:UITableViewStylePlain];
    _searchResultTVC.delegate = self;
    //tvc.view.backgroundColor = [UIColor blueColor];
    
    //创建搜索控制器
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:_searchResultTVC];
    _searchController.searchResultsUpdater = self;
    _searchController.delegate = self;
    _searchController.searchBar.delegate = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.hidesNavigationBarDuringPresentation = NO;
    _searchController.searchBar.frame = CGRectMake(0,0, SCREEN_WIDTH,44);
    _searchController.searchBar.showsCancelButton = YES;
    
    for(id cc in [_searchController.searchBar.subviews[0] subviews]) {
        
        if([cc isKindOfClass:[UIButton class]]) {
            
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
    
    
    _searchController.searchBar.placeholder = MYLocalizedString(@"CHANGECITY_SEARCH", nil);
    
    _searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
    _searchController.searchBar.barTintColor = [UIColor whiteColor];
    _searchController.searchBar.tintColor = [UIColor whiteColor];
    
    [_searchController.searchBar sizeToFit];
    
    CGFloat height;
    if (@available(iOS 11.0, *)) {
        
        height = 32.0f;
        [_searchController.searchBar setSearchFieldBackgroundPositionAdjustment: UIOffsetMake(0, -3)];
    }else{
        height = 32.0f;
    }
    UIImage* searchBarBg = [IGUtils getImageWithColor:[UIColor colorWithWhite:1 alpha:0.3] andHeight:height];
    
    [_searchController.searchBar setBackgroundImage:searchBarBg];
    [_searchController.searchBar setBackgroundColor:[UIColor clearColor]];
    [_searchController.searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
    
    [_searchController.searchBar setImage:[UIImage imageNamed:@"clear_placeholder"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    [_searchController.searchBar setImage:[UIImage imageNamed:@"clear_placeholder"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
    
    UITextField *searchField = [_searchController.searchBar valueForKey:@"searchField"];
    
    
    searchField.tintColor = [UIColor whiteColor];
    searchField.textColor = [UIColor whiteColor];
    searchField.font = Font(14);
    [searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    if (searchField) {
        searchField.layer.cornerRadius = 3.0f;
        searchField.layer.masksToBounds = YES;
    }
    
    UIImage *image = [UIImage imageNamed:@"searchIcon"];
    UIImageView *iconView = [[UIImageView alloc] initWithImage:image];
    iconView.frame = CGRectMake(0, 0, 16 , 16);
    searchField.leftView = iconView;
    _searchController.searchBar.translatesAutoresizingMaskIntoConstraints = false;
    
    self.navigationItem.titleView = _searchController.searchBar;
    
   
}

#pragma mark - search

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    
    if (searchString.length > 0) {
        @weakify(self);
        //过滤数据
        [CityListDAO getCityListWithMatch:searchString block:^(NSArray *cityArray) {
            @strongify(self);
            self.searchResultTVC.searchResultArr = [NSMutableArray arrayWithArray:cityArray];
            //刷新表格
            [self.searchResultTVC.tableView reloadData];
        }];
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    searchBar.placeholder = @"";
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    searchBar.placeholder = MYLocalizedString(@"CHANGECITY_SEARCH", nil);
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma makr - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (section == 0 && (self.gpsCity || self.dataSource.count != 0)) {
        return 1;
    }
    
    if (section == 1 && self.dataSource.count != 0 && self.gpsCity) {
        
        return 1;
    }
    
    NSInteger index = section - self.otherCount;
    
    searchCountyList * county = self.countyListArray[index];
    
    return  county.cities.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    self.otherCount = 0;
    if (self.gpsCity) {
        self.otherCount ++;
    }
    
    if (self.dataSource.count != 0) {
        
        self.otherCount ++;
    }
    
    return self.otherCount + self.countyListArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && self.gpsCity) {
        
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
            cell.textLabel.textColor = kSubitleColor;
            cell.textLabel.font = Font(14);
            cell.imageView.image = [UIImage imageNamed:@"position"];
        }
        cell.textLabel.text = self.gpsCity.smartName;
        
        return cell;
    }
    
    if ((self.gpsCity && self.dataSource.count != 0 && indexPath.section == 1) || (indexPath.section == 0 && !self.gpsCity &&self.dataSource.count != 0)) {
        
        RecommndCityListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecommndCityListCell"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        [cell configData:self.dataSource];
        
        return cell;
    }
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.textColor = kSubitleColor;
    cell.textLabel.font = Font(14);
    
    NSInteger index = indexPath.section - self.otherCount;
    
    searchCountyList * county  = self.countyListArray[index];
    City * city = county.cities[indexPath.row];
    cell.textLabel.text  = city.smartName;
    
    cell.imageView.image = [UIImage imageNamed:@"position"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
     City *city;
    
     if (indexPath.section == 0 && self.gpsCity) {
         
         if (city.cid.integerValue == self.currentCity.cid.integerValue) {
             city = self.currentCity;
         } else {
             city = self.gpsCity;
         }
    }  else if ((self.gpsCity && self.dataSource.count != 0 && indexPath.section == 1) || (indexPath.section == 0 && !self.gpsCity &&self.dataSource.count != 0)) {
        
        return ;
    } else {
        
        NSInteger index = indexPath.section - self.otherCount;
        
        searchCountyList * country = self.countyListArray[index];
        
        city = country.cities[indexPath.row];
        
    }
    
    [self selectCity:city];
}

//- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//
//    NSMutableArray *array = [NSMutableArray array];
//
//    for (searchCountyList * country in self.countyListArray) {
//        [array addObject:[IGUtils firstCharactor:country.smartName]];
//    }
//
//    [array insertObject:@"附近" atIndex:0];
//    [array insertObject:@"当前" atIndex:0];
//
//    return array;
//}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
//    UITableViewHeaderFooterView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HeaderView"];
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UILabel * label = [UILabel new];
    
    [view addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(view.mas_top);
        make.bottom.equalTo(view.mas_bottom);
        make.left.equalTo(view.mas_left).offset(16);
        make.right.equalTo(view.mas_right).offset(-16);
    }];
    
    label.textColor = kContentColor;
    label.font = Font(12);
    
    if ((self.gpsCity && self.dataSource.count != 0 && section == 1) || (section == 0 && !self.gpsCity &&self.dataSource.count != 0)) {
        
        NSString *str1 = self.currentCity.smartName.length > 0 ?[NSString stringWithFormat:@"%@ ",self.currentCity.smartName] : @"";
        NSString *str2 = MYLocalizedString(@"CHANGECITY_NEARBY", nil);
        
        
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",str1,str2]];
        
        [attr addAttribute:NSForegroundColorAttributeName value:kThemeColor range:NSMakeRange(0,  str1.length)];
        
        label.attributedText = attr;
        
    }else if (section == 0 && self.gpsCity) {
        
        label.text = MYLocalizedString(@"CHANGECITY_GPS_LOAD", nil);
    }else {
        
        NSInteger index = section - self.otherCount;
        searchCountyList * county = self.countyListArray[index];
        
        label.text = county.smartName;
    }
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ((self.gpsCity && self.dataSource.count != 0 && indexPath.section == 1) || (indexPath.section == 0 && !self.gpsCity &&self.dataSource.count != 0)) {
        
        return [RecommndCityListCell getHight:self.dataSource];
        
    }else {
        
        return 50;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [_searchController.searchBar endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)cityListSelectCity:(City *)city {
    
    [self selectCity:city];
}
#pragma mark -SearchResultsControllerTableViewController
- (void)selectCity:(City *)city {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
    if ([_delegate respondsToSelector:@selector(selectCity:)]) {
        [_delegate selectCity:city];
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
